import ListFix from "../../ListFix";
import { location } from "../utils/getLocation";
import { guiMover } from "../utils/gui";
import settings from "../utils/settings";
import { DrawString, RemoveEmoji, getItemFromGui, getItemSBID } from "../utils/utils";

export let sack = {}

function saveFile() {
    FileLib.write("./config/ChatTriggers/modules/BabyzombieAddons/config/sacks.json",JSON.stringify(sack,null,4),true);
}

if(FileLib.isDirectory("./config/ChatTriggers/modules/BabyzombieAddons/config") && FileLib.exists("./config/ChatTriggers/modules/BabyzombieAddons/config/sacks.json")) {
    try {
        sack = Object.assign(sack,JSON.parse(FileLib.read("./config/ChatTriggers/modules/BabyzombieAddons/config/sacks.json")));
    } catch (error) {}
}

let LastGuiName = "";
let LastGuiOpen = 0;
register("guiOpened", () => {
    if(!location.inSkyblock) return;
    getItemInSacks.register();
    LastGuiOpen = Date.now();
})
register("worldLoad",()=>{
    getItemInSacks.unregister();
    LastGuiOpen = Date.now();
})
register("step", () => {
    if(LastGuiOpen + 2000 < Date.now()) getItemInSacks.unregister();
})

const getItemInSacks = register("renderItemIntoGui", (item,x,y,event) => {
    if(!location.inSkyblock || item.getName().removeFormatting() != "Go Back") return;
    try {
        const gui = Player.getContainer();
        if(!gui) return;
        const SackName = gui.getName().removeFormatting();
        if(LastGuiName === SackName) return;
        LastGuiName = SackName;
        if(!SackName.endsWith("Sack") || SackName == "Runes Sack") return;
        let ItemList = gui.getItems();
        if(ItemList.filter(e => e && e.getName() == "§aGo Back" && e.getLore()[1].includes("§7To Sack of Sacks")).length == 0) return;
        let Items = ItemList.filter(e => e && e.getName() && getItemSBID(e) && e.getLore().filter(e => e && e.removeFormatting().startsWith("Stored: ")).length == 1);
        const profileID = location.SBProfile;
        if(!sack[profileID]) sack[profileID] = {};
        Items.forEach(e => {
            let itemName = e.getName().removeFormatting();
            if(SackName == "Gemstones Sack") {
                e.getLore().filter(s => s && s.removeFormatting().search(/ [a-zA-Z]+: [0-9,]+ \([0-9+,]+\)/) === 0).forEach(s => {
                    const name = s.removeFormatting().trim().replace(/: [0-9,]+ \([0-9+,]+\)/,'') + ' ' + itemName.replace("Gemstones","Gemstone");
                    if(sack[profileID][name] == undefined) sack[profileID][name] = {stored:0,show:false};
                    sack[profileID][name].stored = parseInt(s.removeFormatting().replace(/ [a-zA-Z]+: /,'').replace(/ \([0-9+,]+\)/,'').replace(/,/g,""));
                })
            } else {
                if(SackName.includes("Trophy Fishing")) itemName += " " + SackName.split(" ")[0].toUpperCase();
                if(sack[profileID][itemName] == undefined) sack[profileID][itemName] = {stored:0,show:false};
                sack[profileID][itemName].stored = parseInt(e.getLore().filter(s => s && s.removeFormatting().startsWith("Stored: "))[0].removeFormatting().replace("Stored: ","").replace(/\/[\w]+/,"").replace(/,/g,""));    
            }
        })
        saveFile();
        updateSackItemsString();
        getItemInSacks.unregister();
    } catch (error) {} 
}).unregister()

let itemReg = /  ([+-][0-9,]+) (.+) \([a-zA-Z ,]+ Sack\)/i;
register("chat", (n,s,t,event) => {
    if(!location.inSkyblock) return;
    try {
        const message = new Message(event);
        const profileID = location.SBProfile;
        if(!sack[profileID]) sack[profileID] = {};
        message.getMessageParts().filter(e => e && e.getText().includes("item") && e.getHoverValue() && e.getHoverValue().includes("Sack")).forEach(TextComponent => {
            TextComponent.getHoverValue().removeFormatting().split('\n').forEach(item => {
                const stringArray = item.match(itemReg);
                if(stringArray == null) return;
                const number = stringArray[1].replace(/,/g,"");
                const itemName = RemoveEmoji(stringArray[2].removeFormatting().replace("§L","")).trim();
                if(sack[profileID][itemName] == undefined) sack[profileID][itemName] = {stored:0,show:false};
                if (number[0] === "+") sack[profileID][itemName].stored += parseInt(number.replace("+",""));
                else if (number[0] === "-") sack[profileID][itemName].stored -= parseInt(number.replace("-",""));
                if(sack[profileID][itemName] < 0) sack[profileID][itemName].stored = 0;
            })
            saveFile();
            updateSackItemsString();
        })
        if(settings.showSackItems == 2) cancel(event);
    } catch (error) {}
}).setCriteria("[Sacks] ${n} item${s} (Last ${t}s.)")

let sackItemsToShow = "";
function updateSackItemsString() {
    if(!location.inSkyblock) return;
    try {
        sackItemsToShow = "";
        for (let itemName in sack[location.SBProfile]) {
            if(sack[location.SBProfile][itemName].show) {
                if(itemName.startsWith("Rough") && itemName.endsWith("Gemstone")) {
                    let flawed = sack[location.SBProfile][itemName.replace("Rough ","Fine ")].stored * 80 + sack[location.SBProfile][itemName.replace("Rough ","Flawed ")].stored;
                    sackItemsToShow += "§b" + itemName.replace("Rough ","") + "§7:§e " + (sack[location.SBProfile][itemName].stored + flawed * 80).toString().replace(/\B(?=(?:\d{3})+\b)/g, ',') + "\n";
                } else sackItemsToShow += "§b" + itemName + "§7:§e " + sack[location.SBProfile][itemName].stored.toString().replace(/\B(?=(?:\d{3})+\b)/g, ',') + "\n";
            }
        }
        if(sackItemsToShow != "") sackItemsToShow = "§b§lSack Items:\n" + sackItemsToShow;
    } catch (error) {}
}
register("worldLoad", updateSackItemsString);
updateSackItemsString();

register(net.minecraftforge.event.entity.player.ItemTooltipEvent, event => {
    try {
        if(!settings.showSackItems || !location.inSkyblock) return;
        const Container = Player.getContainer();
        if(!Container) return;
        const SackName = Container.getName().removeFormatting();
        if(!SackName.endsWith("Sack") || SackName == "Runes Sack") return;
        let item = new Item(event.itemStack);
        if(getItemSBID(item) == "") return;
        let itemName = item.getName().removeFormatting();
        if(SackName.includes("Trophy Fishing")) itemName += " " + SackName.split(" ")[0].toUpperCase();
        if(SackName == "Gemstones Sack") itemName = "Rough " + itemName.replace("Gemstones","Gemstone");
        if(sack[location.SBProfile][itemName] == undefined) return;
        if(sack[location.SBProfile][itemName].show) {
            ListFix.add(event,"toolTip","§eCtrl + 左键点击以隐藏此物品的数量显示");
            ListFix.add(event,"toolTip","§b此物品的数量将在hud显示");
        } else ListFix.add(event,"toolTip","§eCtrl + 左键点击以显示此物品数量在hud");
    } catch (error) {}
})

register("guiMouseClick", (mx,my,button,gui,event) => {
    try {
        if(!settings.showSackItems || !location.inSkyblock || !Keyboard.isKeyDown(Keyboard.KEY_LCONTROL) || button != 0) return;
        const Container = Player.getContainer();
        if(!Container) return;
        const SackName = Container.getName().removeFormatting();
        if(!SackName.endsWith("Sack") || SackName == "Runes Sack") return;
        let item = getItemFromGui(gui);
        if(getItemSBID(item) == "") return;
        let itemName = item.getName().removeFormatting();
        if(SackName.includes("Trophy Fishing")) itemName += " " + SackName.split(" ")[0].toUpperCase();
        if(SackName == "Gemstones Sack") itemName = "Rough " + itemName.replace("Gemstones","Gemstone");
        if(sack[location.SBProfile][itemName] == undefined) return;
        sack[location.SBProfile][itemName].show = !sack[location.SBProfile][itemName].show;
        cancel(event);
        saveFile();
        updateSackItemsString();
    } catch (error) {}
})

register("renderOverlay", (event) => {
    if(!settings.showSackItems) return;
    if(guiMover.gui.isOpen()) {
        DrawString("§b§lSack Items:\n§bJade Gemstone§7:§e 25565\n§bNether Star§7:§e 888", guiMover.settings.showSackItems.x, guiMover.settings.showSackItems.y, guiMover.settings.showSackItems.s, true);
        return;
    }
    if(!settings.showSackItems || !location.inSkyblock || !sackItemsToShow) return;
    DrawString(sackItemsToShow, guiMover.settings.showSackItems.x, guiMover.settings.showSackItems.y, guiMover.settings.showSackItems.s, true);
})